<template>
	<Modal scrollable v-model="modal" @on-cancel="onCancel" :title="$t('page.customer.add_customer')"
		class-name="vertical-center-modal" width="950">
		<Form ref="formDynamic" :model="formDynamic" :rules="rules" class="attrFrom" :label-width="labelWidth"
			:label-position="labelPosition" @submit.native.prevent>
			<Row :gutter="24">
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.frist_name')+'：'" prop="first_name" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_first_name')" :maxlength="50" show-word-limit
						v-model="formDynamic.first_name" />
				</FormItem>
				</Col>



				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.last_name')+'：'" prop="last_name" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_last_name')" :maxlength="50" show-word-limit
						v-model="formDynamic.last_name" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.language')+'：'" prop="language" class="vertical-layout">
					<Select v-model="formDynamic.language" clearable>
						<Option v-for="item in languagesList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.phone')+'：'" prop="phone" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_phone')" :maxlength="20" show-word-limit
						v-model="formDynamic.phone" @on-blur="checkPhoneExist" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.email')+'：'" prop="email" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_email')" :maxlength="32" show-word-limit
						v-model="formDynamic.email" @on-blur="checkEmailExist" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.country_or_region')+'：'" prop="country" class="vertical-layout">
					<Select @on-change="onCountryChange" v-model="formDynamic.country">
						<Option v-for="item in countryList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.company')+'：'" prop="company" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_company')" :maxlength="32" show-word-limit
						v-model="formDynamic.company" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.address')+'：'" prop="address" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_address')" :maxlength="50" show-word-limit
						v-model="formDynamic.address" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.apartment_suit_etc')+'：'" prop="apartment" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_aprtment')" :maxlength="20" show-word-limit
						v-model="formDynamic.apartment" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.city')+'：'" prop="city" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_city')" :maxlength="20" show-word-limit
						v-model="formDynamic.city" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.state')+'：'" prop="state" class="vertical-layout">
					<Select v-model="formDynamic.state" clearable>
						<Option v-for="item in statesList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.zip_code')+'：'" prop="zip_code" class="vertical-layout">
					<Input :placeholder="$t('page.customer.input_zip_code')" :maxlength="20" show-word-limit
						v-model="formDynamic.zip_code" />
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.customer_voucher')+':'" class="vertical-layout">
					<p>
						<Upload :action="fileUrl" :headers="header" :max-size="5*1024" :max-length="2" :multiple="true"
							:on-success="handleSuccess" :file-list="uploadFileList">
							<Button icon="ios-cloud-upload-outline">{{$t('page.customer.upload_files')}}</Button>
						</Upload>
						<el-image v-for="(url, index) in images" :key="index"
							style="width: 50px; height: 50px; margin-right: 5px" :src="url" :preview-src-list="urlList"
							:z-index="1"></el-image>
					<div v-for="(file, index) in others" :key="index" class="file-item">
						📄 {{ getFileName(file) }}
					</div>
					</p>
				</FormItem>
				</Col>
				</Col>
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem :label="$t('page.customer.tag')+'：'" prop="tag" class="vertical-layout">
					<!-- <el-button @click="dialogVisible = true">Add Tags</el-button> -->
					<!-- 打开弹窗按钮 -->
					<Button type="primary" @click="dialogVisible = true">{{$t('page.customer.add_new_tag')}}</Button>
					<!-- 已选择的标签展示 -->
					<div style="margin: 15px 0;">
						<span v-if="formDynamic.selectedTags.length">{{$t('page.customer.selected_tag')}}：</span>
						<Tag v-for="(tag, index) in formDynamic.selectedTags" :key="index" closable
							@on-close="removeTag(tag)" style="margin-right: 8px; margin-bottom: 8px;">
							{{ tag.label }}
						</Tag>
						<span v-if="!formDynamic.selectedTags.length"
							style="color: #999;">{{$t('page.customer.no_tag')}}</span>
					</div>
					<tag-selector v-model="dialogVisible" :tags="tagsList" :selected="formDynamic.selectedTags"
						@save="handleSaveTags" />
				</FormItem>
				</Col>
				</Col>
			</Row>

		</Form>
		<div slot="footer">
			<Button type="primary" @click="cancle">{{$t('page.product.cancel')}}</Button>
			<Button type="primary" :loading="modal_loading"
				@click="handleSubmit('formDynamic')">{{$t('page.product.save')}}</Button>
		</div>
	</Modal>
</template>

<script>
	import TagSelector from './tagSelector.vue';
	import {
		mapState
	} from "vuex";
	import {
		storeCustomreAddApi,
		storeCustomerInfoApi,
		checkPhoneExistApi,
		checkEmailExistApi
	} from "@/api/storeCustomer";
	import Setting from "@/setting";
	import util from "@/libs/util";
	export default {
		name: "addAttr",
		components: {
			TagSelector
		},
		props: {
			languagesList: {
				type: Array,
				default: () => []
			},
			statesList: {
				type: Array,
				default: () => []
			},
			countryList: {
				type: Array,
				default: () => []
			},
			tagsList: {
				type: Array,
				default: () => []
			},
		},
		data() {
			return {
				header: {},
				fileUrl: Setting.apiBaseURL + "/file/upload",
				spinShow: false,
				modal_loading: false,
				dialogVisible: false,
				// allTags: [
				//         {
				// 			label:"标签一",
				// 			value:"1"
				// 		},
				// 		{
				// 			label:"标签二",
				// 			value:"2"
				// 		},
				//       ],
				grid: {
					xl: 3,
					lg: 3,
					md: 12,
					sm: 24,
					xs: 24,
				},
				modal: false,
				index: 1,
				// rules: {
				// 	rule_name: [{
				// 		required: true,
				// 		message: $t('page.product.please_category'),
				// 		trigger: "blur"
				// 	}, ],
				// 	first_name: [{
				// 		required: true,
				// 		message: $t('page.customer.input_first_name'),
				// 		trigger: "blur"
				// 	}, ],
				// 	last_name: [{
				// 		required: true,
				// 		message: $t('page.customer.input_last_name'),
				// 		trigger: "blur"
				// 	}, ],
				// 	phone: [{
				// 		required: true,
				// 		message: $t('page.customer.input_phone'),
				// 		trigger: "blur"
				// 	}, ],
				// 	company: [{
				// 		required: true,
				// 		message: $t('page.customer.input_company'),
				// 		trigger: "blur"
				// 	}, ],
				// 	address: [{
				// 		required: true,
				// 		message: $t('page.customer.input_address'),
				// 		trigger: "blur"
				// 	}, ],
				// 	email: [{
				// 			required: true,
				// 			message: $t('page.customer.input_email'),
				// 			trigger: 'blur'
				// 		},
				// 		{
				// 			pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
				// 			message: $t('page.customer.email_format_incorrect'),
				// 			trigger: 'blur'
				// 		}
				// 	]
				// },
				phoneExist: false,
				emailExist: false,
				formDynamic: {
					first_name: "",
					last_name: "",
					phone: "",
					email: "",
					address: "",
					language: "1",
					state: "1",
					country: "20",
					company: "",
					apartment: "",
					city: "",
					zip_code: "",
					selectedTags: [],
					file_url: [],
				},
				uploadFileList: [],
				images: [],
				others: [],
				urlList: [],
				attrsName: "",
				attrsVal: "",
				formDynamicNameData: [],
				isBtn: false,
				formDynamicName: [],
				results: [],
				result: [],
				ids: 0,
				title: "添加客户信息",
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile"]),
			labelWidth() {
				return this.isMobile ? undefined : 150;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			rules(){
				return {
					rule_name: [{
						required: true,
						message: $t('page.product.please_category'),
						trigger: "blur"
					}, ],
					first_name: [{
						required: true,
						message: $t('page.customer.input_first_name'),
						trigger: "blur"
					}, ],
					last_name: [{
						required: true,
						message: $t('page.customer.input_last_name'),
						trigger: "blur"
					}, ],
					phone: [{
						required: true,
						message: $t('page.customer.input_phone'),
						trigger: "blur"
					}, ],
					company: [{
						required: true,
						message: $t('page.customer.input_company'),
						trigger: "blur"
					}, ],
					address: [{
						required: true,
						message: $t('page.customer.input_address'),
						trigger: "blur"
					}, ],
					email: [{
							required: true,
							message: $t('page.customer.input_email'),
							trigger: 'blur'
						},
						{
							pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
							message: $t('page.customer.email_format_incorrect'),
							trigger: 'blur'
						}
					],
				}
			}
		},
		mounted() {
			this.getToken();
		},
		methods: {
			// ...mapMutations('store/layout', [
			//     'setCopyrightShow'
			// ]),
			getToken() {
				this.header["Authori-zation"] = "Bearer " + util.cookies.get("token");
			},
			// 上传成功
			handleSuccess(res, file, fileList) {
				this.fileGouzi = file
				console.log("this.formDynamic.file_url", this.formDynamic.file_url)
				if (res.code === 0) {
					if (!Array.isArray(this.formDynamic.file_url)) {
						this.formDynamic.file_url = [];
					}
					// this.formDynamic.file_url = res.data.src;
					this.formDynamic.file_url.push(res.data.src)
					this.$Message.success(res.msg);
				} else {
					this.$Message.error(res.msg);
				}
			},
			getFileName(url) {
				try {
					return url.split('/').pop();
				} catch (e) {
					return url;
				}
			},
			//检查手机是否存在
			checkPhoneExist() {
				let data = {
					id: this.ids,
					phone: this.formDynamic.phone
				}
				console.log("data", data)
				checkPhoneExistApi(data)
					.then((res) => {
						console.log("res---", res)
						if (res.data.exists) {
							this.phoneExist = true
							this.formDynamic.phone = ""
							this.$Message.warning($t('page.customer.phone_exists'))
						} else {
							this.phoneExist = false
						}
					})
					.catch((res) => {
						this.$Message.error($t('page.customer.phone_check_fail'));
					});
			},
			checkEmailExist() {
				// alert(123)
				let data = {
					id: this.ids,
					email: this.formDynamic.email
				}
				checkEmailExistApi(data)
					.then((res) => {
						console.log("res1---", res)
						if (res.data.exists) {
							this.emailExist = true
							this.formDynamic.email = ""
							this.$Message.warning($t('page.customer.email_exit'))
						} else {
							this.emailExist = false
						}
					})
					.catch((res) => {
						this.$Message.error($t('page.customer.email_check_fail'));
					});
			},
			removeTag(tag) {
				// 移除单个标签
				this.formDynamic.selectedTags = this.formDynamic.selectedTags.filter(t => t !== tag);
			},
			handleSaveTags(tags) {
				this.formDynamic.selectedTags = tags;
				console.log('保存的标签:', tags);
			},
			onCountryChange(value) {
				console.log('国家变更，传给父组件的值：', value);
				// 触发事件传给父组件
				this.$emit('countryChanged', value);
			},
			onCancel() {
				this.clear();
			},
			// getLanguagesList(){

			// 		  languagesListApi(this.formDynamic).then((res) => {
			// 			  this.languagesList = res.data.list;
			// 		  }).catch((err)=>{
			// 		    // this.loading = false;
			// 		    this.$Message.error(err.msg);
			// 		  })

			// },
			// 添加按钮
			addBtn() {
				if (this.formDynamic.rule_name.trim() == '') {
					return this.$Message.error('请输入分类名称');
				}
				this.isBtn = true;
			},
			// 详情
			getIofo(row) {
				this.spinShow = true;
				this.ids = row.id;
				this.title = "编辑客户";
				storeCustomerInfoApi(row.id)
					.then((res) => {
						this.formDynamic = res.data.info;
						// this.splitFilesByType(res.data.info.file_url)
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			isImageFile(url) {
				const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
				const ext = url.split('.').pop().toLowerCase();
				return imageTypes.includes(ext);
			},

			splitFilesByType(fileArray) {
				if (!Array.isArray(this.formDynamic.images)) {
					this.images = [];
				}
				console.log('filearr', fileArray)
				fileArray.forEach(url => {

					if (this.isImageFile(url)) {
						this.images.push(url);
						console.log('this.images', this.images);
					} else {
						this.others.push(url);
						console.log('this.others', this.others);
					}
				});
				console.log('images', this.images)
				// return { images, others };
			},
			// 提交
			handleSubmit(name) {
				this.$refs[name].validate((valid) => {
					if (!valid) return;
					if (valid) {
						if (this.phoneExist) {
							return this.$Message.warning($t('page.customer.phone_exists'));
						}
						if (this.emailExist) {
							return this.$Message.warning($t('page.customer.email_exit'));
						}
						if (this.formDynamic.first_name.length == 0) {
							return this.$Message.warning($t('page.customer.input_customer'));
						}
						if (this.formDynamic.address.length == 0) {
							return this.$Message.warning($t('page.customer.input_address'));
						}
						if (this.formDynamic.email.length == 0) {
							return this.$Message.warning($t('page.customer.search_email'));
						}
						if (this.formDynamic.phone.length == 0) {
							return this.$Message.warning($t('page.customer.input_phone'));
						}

						this.modal_loading = true;

						setTimeout(() => {
							storeCustomreAddApi(this.formDynamic, this.ids)
								.then((res) => {
									this.$Message.success(res.msg);
									setTimeout(() => {
										this.modal = false;
										this.modal_loading = false;
									}, 500);
									setTimeout(() => {
										this.$emit("getList");
										this.clear();
									}, 600);
								})
								.catch((res) => {
									this.modal_loading = false;
									this.$Message.error(res.msg);
								});
						}, 1200);
					} else {
						return false;
					}
				});
			},
			clear() {
				this.$refs["formDynamic"].resetFields();
				this.formDynamic.spec = [];
				this.formDynamic.first_name = "";
				this.formDynamic.last_name = "";
				this.formDynamic.phone = "";
				this.formDynamic.email = "";
				this.formDynamic.address = "";
				this.formDynamic.language = "1";
				this.formDynamic.state = "1";
				this.formDynamic.country = "20";
				this.formDynamic.company = "";
				this.formDynamic.apartment = "";
				this.formDynamic.city = "";
				this.formDynamic.zip_code = "";
				this.formDynamic.selectedTags = [];
				this.formDynamic.file_url = [];
				console.log("this.formDynamic.file_urlqqq", this.formDynamic.file_url)
				this.isBtn = false;
				this.ids = 0;
				this.title = "添加客户";
				this.attrsName = "";
				this.attrsVal = "";
				this.images = [];
				this.others = [];
				this.urlList = [];
				this.uploadFileList = [];
				this.$nextTick(function() {
					if (_this6.$refs.uploadRef) {
						_this6.$refs.uploadRef.clearFiles();
					}
				});
			},
			// 取消
			offAttrName() {
				this.isBtn = false;
			},
			cancle() {
				this.modal = false;
				this.clear()
			},
			// 删除
			handleRemove(index) {
				this.formDynamic.spec.splice(index, 1);
			},
			// 删除属性
			handleRemove2(item, index) {
				item.splice(index, 1);
			},
			// 添加规则名称
			createAttrName() {
				if (this.attrsName && this.attrsVal) {
					let data = {
						value: this.attrsName,
						detail: [this.attrsVal],
					};
					this.formDynamic.spec.push(data);
					var hash = {};
					this.formDynamic.spec = this.formDynamic.spec.reduce(function(
							item,
							next
						) {
							/* eslint-disable */
							hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
							return item;
						},
						[]);
					this.attrsName = "";
					this.attrsVal = "";
					this.isBtn = false;
				} else {
					this.$Message.warning("请添加规格名称或规格值");
				}
			},
			// 添加属性
			createAttr(num, idx) {
				if (num) {
					this.formDynamic.spec[idx].detail.push(num);
					var hash = {};
					this.formDynamic.spec[idx].detail = this.formDynamic.spec[
						idx
					].detail.reduce(function(item, next) {
						/* eslint-disable */
						hash[next] ? "" : (hash[next] = true && item.push(next));
						return item;
					}, []);
				} else {
					this.$Message.warning("请添加属性");
				}
			},
		},
	};
</script>

<style scoped lang="stylus">
	.rulesBox {
		display: flex;
		align-items center;
		flex-wrap: wrap;
	}

	.attrFrom {
		>>>.ivu-form-item {
			margin-bottom: 0px !important;
		}
	}

	.sub {
		text-align right margin 20px 0 0 20px
	}

	.vertical-layout {
		display: block !important;
		/* 覆盖默认的 flex 布局 */
	}

	/* 标签样式 */
	.vertical-layout>>>.ivu-form-item-label {
		float: none !important;
		/* 取消浮动 */
		display: block !important;
		/* 块级显示 */
		width: 100% !important;
		/* 占满宽度 */
		text-align: left !important;
		/* 左对齐 */
		padding: 0 0 10px 0 !important;
		/* 底部间距 */
		margin-bottom: 10px;
		/* 增加与内容的间距 */
		border-bottom: 1px solid #eee;
		/* 可选：添加分隔线 */
		font-weight: bold;
		/* 加粗显示 */
	}

	/* 内容区域样式 */
	.vertical-layout>>>.ivu-form-item-content {
		display: block !important;
		/* 块级显示 */
		margin-left: 0 !important;
		/* 清除左侧间距 */
		clear: both;
		/* 清除浮动 */
	}

	.vertical-layout {
		margin-top: 7px !important;
	}
</style>